package com.liukunup.distance;

import com.liukunup.bean.Rect;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

/**
 * 交并比 IOU
 * Intersection-over-Union
 * @author Liu Kun
 * @date 2021-04-03 20:26:05
 **/
@Slf4j
public class IoU {

    /**
     * 计算两个矩形框重叠面积
     * 如果无重叠区域则返回0
     * 矩形必须以 左上角+右下角 坐标方式描述
     * @param a 矩形框A
     * @param b 矩形框B
     * @return 重叠度
     */
    public static double calc(@NonNull Rect<Double> a, @NonNull Rect<Double> b) {
        // 计算两个已知矩形面积
        double areaOfRect1 = Area.calc(a);
        double areaOfRect2 = Area.calc(b);
        log.info("The area of origin rect: a={} b={}.", areaOfRect1, areaOfRect2);
        // 计算重合边界
        double lineTop = Math.max(a.getLeftTop().getY(), b.getLeftTop().getY());
        double lineBottom = Math.min(a.getRightBottom().getY(), b.getRightBottom().getY());
        double lineLeft = Math.max(a.getLeftTop().getX(), b.getLeftTop().getX());
        double lineRight = Math.min(a.getRightBottom().getX(), b.getRightBottom().getX());
        // 计算交集面积
        double areaOfIntersection = Math.max(lineBottom - lineTop, 0) * Math.max(lineRight - lineLeft, 0);
        log.info("The area of intersection rect: {}.", areaOfIntersection);
        // 计算重合度
        return areaOfIntersection * 1.0f / (areaOfRect1 + areaOfRect2 - areaOfIntersection);
    }
}